package com.wing.actor;

import java.util.concurrent.ArrayBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Actor调度器
 * @author 杜祥
 * @create 2017年9月11日
 */
public class ActorWorkerDispatcher implements Runnable
{
	private final static Logger log = LoggerFactory.getLogger(ActorWorkerDispatcher.class);
	
	
	/**
	 * 是否在运行中
	 */
	private volatile boolean run;
	
	/**
	 * Actor队列
	 */
	private final ArrayBlockingQueue<AbstractActor> actorQueue;
	
	
	/**
	 * Actor调度属于的Actor管理类
	 */
	private ActorManager parent;
	
	
	
	public ActorWorkerDispatcher(int maxCount, ActorManager parent)
	{
		this.run = true;
		this.parent = parent;
		this.actorQueue = new ArrayBlockingQueue<AbstractActor>(maxCount);
	}
	
	
	
	
	/**
	 * 所属的Actor管理器
	 * @return
	 */
	public ActorManager getParent()
	{
		return parent;
	}




	/**
	 * 增加一个Actor
	 * @param actor
	 * @return
	 */
	boolean addActor(AbstractActor actor) 
	{
		if(!run) 
		{
			return false;
		}
		return actorQueue.offer(actor);
	}
	
	
	
	
	@Override
	public void run()
	{
		while(run) 
		{
			try
			{
				AbstractActor actor;
				
				actor = actorQueue.take();
				
				if(!actor.hasActive()) 
					continue;
				
				if(actor.getActorState() == ActorState.WORKER) 
				{
					actor.worker();
				}
				else if(actor.getActorState() == ActorState.START) 
				{
					actor.startup();
				}
				else 
				{
					log.warn("Actor[{}] 处于状态[{}], 没有对应的操作执行。", actor.toString(), actor.getActorState());
				}
			}
			catch (InterruptedException e)
			{
				log.error("线程中断。", e);
				shutdown();
				return ;
			}
			catch (Throwable e)
			{
				log.error("ActorWorkerDispatch run error.", e);
			}
		}
	}
	
	
	
	/**
	 * 停止此调度器
	 */
	void shutdown() 
	{
		run = false;
		
		actorQueue.clear();
		
		parent = null;
	}
	
	
	/**
	 * 调度器是否停止
	 * @return
	 */
	public boolean isShutdown()
	{
		return run;
	}
	

}
